package com.example.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {
    public abstract Class getChildClass();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        Class childClass = getChildClass();
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            String action = req.getParameter("action");
            Method method = childClass.getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            Object invoke = method.invoke(childClass.newInstance(), req, resp);
            if(invoke instanceof String){
                String url=String.valueOf(invoke);
                req.getRequestDispatcher(url+".jsp").forward(req,resp);
            } else if (invoke instanceof ResultData) {
                ResultData resultData=(ResultData) invoke;
                String jsonString = JSON.toJSONString(resultData);
                PrintWriter writer = resp.getWriter();
                writer.write(jsonString);
                writer.flush();
            } else if (invoke instanceof InitResult) {
                InitResult initResult=(InitResult) invoke;
                String jsonString = JSON.toJSONString(initResult);
                PrintWriter writer = resp.getWriter();
                writer.write(jsonString);
                writer.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
